<template>
  <div class="default-main page">
    <PageSearch
      ref="pageSearchRef"
      :pageName="pageName"
      :searchConfig="searchConfigComputed"
    ></PageSearch>
    <PageContent
      ref="pageContentRef"
      :pageName="pageName"
      :contentConfig="contentConfigComputed"
      :autoDesc="false"
      :dictMap="dictMap"
      :tableListener="tableListener"
      :tableSelected="tableSelected"
      :permission="permission"
      :requestBaseUrl="requestBaseUrl"
      :tableHideItems="tableHideItems"
      :idKey="'logId'"
      @beforeSend="beforeSend"
      @addClick="addClick"
      @editBtnClick="editBtnClick"
      @onChangeShowColumn="onChangeShowColumn"
      @deleteClick="handleDelete"
      @editMoreClick="editMoreClick"
    >
      <template #handleLeft>
        <el-button
          type="warning"
          class="ml12 order16"
          v-hasPermi="['system:operations:export']"
          @click="handleExport"
        >
          <SvgIcon size="14" iconClass="download" />
          <span class="ml6">导出</span>
        </el-button>
      </template>
    </PageContent>
    <PageDialog
      ref="dialogRef"
      :width="getWidth(dialogWidth)"
      :pageName="pageName"
      :dialogConfig="dialogConfigComputed"
      :infoInit="infoInit"
      :search="search"
      :isEditMore="isEditMore"
      :requestBaseUrl="requestBaseUrl"
      @editNext="editNext"
      @beforeCommit="handleBeforeCommit"
    >
    </PageDialog>
  </div>
</template>

<script setup name="Operations">
import { nextTick } from 'vue'
import { listOperations, getOperations, delOperations, addOperations, updateOperations } from "@/api/system/operations"
import useDialog from '@/hooks/useDialog'
import getComputedConfig from '@/hooks/getPageConfig'
import { inject } from 'vue'
import to from '@/utils/to'
import { systemBaseUrl } from '@/api/config/base.js'
import getSearchConfig from './config/searchConfig'
import getContentConfig from './config/contentConfig'
import getDialogConfig from './config/dialogConfig'

const proxy = inject('proxy')
const { file_operations_type, file_type } = proxy.useDict('file_operations_type', 'file_type')

// 打印数据字典的内容，用于调试
console.log('操作类型数据字典内容:', JSON.stringify(file_operations_type.value))

// 页面名称
const pageName = 'operations'
// 请求基础URL
const requestBaseUrl = systemBaseUrl
// 页面搜索组件引用
const pageSearchRef = ref(null)
// 页面内容组件引用
const pageContentRef = ref(null)

// 对话框需要隐藏的项
const dialogHideItems = ref([])
// 表格需要隐藏的项
const tableHideItems = ref([])
// 数据字典映射
const dictMap = {
  operationType: file_operations_type,
  fileType: file_type
}

// 搜索配置
const searchConfig = getSearchConfig()
const searchConfigComputed = computed(() => {
  return getComputedConfig(searchConfig, dictMap)
})

// 表格选中项
const tableSelected = ref([])
// 表格事件监听
const tableListener = {
  selectionChange: (selected) => {
    tableSelected.value = selected
  },
}

// 内容配置
const contentConfig = getContentConfig()
const contentConfigComputed = computed(() => {
  contentConfig.hideItems = tableHideItems
  return contentConfig
})

// 对话框配置
const dialogConfig = getDialogConfig()
const dialogConfigComputed = computed(() => {
  dialogConfig.hideItems = dialogHideItems
  return getComputedConfig(dialogConfig, dictMap)
})

/** 添加回调函数 */
const addCallBack = () => {
  dialogHideItems.value.length = 0
}

/** 编辑回调函数 */
const editCallback = (item, type, res) => {
  console.log('编辑回调被触发', JSON.stringify(item), type, res)
  
  // 检查对象中的ID字段
  console.log('编辑项中的所有字段:', Object.keys(item))
  
  // 检查可能的ID字段
  const possibleIdFields = ['logId', 'operationsId', 'id', 'operationId'];
  let idFieldFound = null;
  
  for (const field of possibleIdFields) {
    if (item[field] !== undefined) {
      idFieldFound = field;
      console.log(`在编辑数据中找到ID字段: ${field} = ${item[field]}`);
    }
  }
  
  // 重置隐藏项
  dialogHideItems.value = []
  isEditMore.value = type
  
  // 确保必要字段存在
  nextTick(() => {
    if (dialogRef.value && dialogRef.value.formData) {
      console.log('编辑初始表单数据:', JSON.stringify(dialogRef.value.formData))
      
      // 确保ID字段存在
      if (idFieldFound && !dialogRef.value.formData[idFieldFound] && item[idFieldFound]) {
        dialogRef.value.formData[idFieldFound] = item[idFieldFound];
        console.log(`设置ID字段 ${idFieldFound} = ${item[idFieldFound]}`);
      }
      
      // 确保必填字段存在
      const requiredFields = ['logId', 'operationsId', 'id', 'operationType', 'operationContent', 'userId'];
      let missingFields = [];
      
      requiredFields.forEach(field => {
        if (dialogRef.value.formData[field] === undefined && item[field] !== undefined) {
          // 特殊处理操作类型字段，转换为标签文本
          if (field === 'operationType') {
            // 从数据字典中查找对应标签
            try {
              const originalType = item[field];
              const typeDict = file_operations_type.value || [];
              console.log('编辑时操作类型原始值:', originalType, '类型:', typeof originalType);
              console.log('编辑时可用的操作类型字典:', JSON.stringify(typeDict));
              
              const typeValue = typeof originalType === 'string' ? parseInt(originalType, 10) : originalType;
              const matchItem = typeDict.find(item => {
                const itemValue = typeof item.value === 'string' ? parseInt(item.value, 10) : item.value;
                return itemValue === typeValue;
              });
              
              if (matchItem) {
                console.log(`编辑时成功转换操作类型: ${originalType}(ID) => ${matchItem.label}(文本)`);
                dialogRef.value.formData[field] = matchItem.label; // 使用标签文本
              } else {
                console.error(`编辑时未找到匹配的操作类型! 原始值: ${originalType}`);
                dialogRef.value.formData[field] = item[field]; // 使用原始值作为后备
              }
            } catch (error) {
              console.error('编辑时操作类型转换出错:', error);
              dialogRef.value.formData[field] = item[field]; // 出错时使用原始值
            }
          } else {
            // 其他字段正常处理
            dialogRef.value.formData[field] = item[field];
          }
          
          console.log(`从item中获取字段: ${field} = ${dialogRef.value.formData[field]}`);
          missingFields.push(field);
        }
      });
      
      if (missingFields.length > 0) {
        console.warn('已填充字段:', missingFields.join(', '));
      }
      
      // 特殊处理：如果操作类型已经存在但可能是ID值，也需要转换
      if (dialogRef.value.formData.operationType !== undefined) {
        try {
          const originalType = dialogRef.value.formData.operationType;
          
          // 检查是否是数字或可转换为数字的字符串
          if (typeof originalType === 'number' || /^\d+$/.test(String(originalType))) {
            const typeDict = file_operations_type.value || [];
            const typeValue = typeof originalType === 'string' ? parseInt(originalType, 10) : originalType;
            
            const matchItem = typeDict.find(item => {
              const itemValue = typeof item.value === 'string' ? parseInt(item.value, 10) : item.value;
              return itemValue === typeValue;
            });
            
            if (matchItem) {
              console.log(`编辑时转换已存在的操作类型: ${originalType}(ID) => ${matchItem.label}(文本)`);
              dialogRef.value.formData.operationType = matchItem.label;
            }
          }
        } catch (error) {
          console.error('处理已存在的操作类型时出错:', error);
        }
      }
    }
  })
}

// 是否批量编辑
const isEditMore = ref(false)

/** 多选编辑按钮点击 */
const editMoreClick = () => {
  if (tableSelected.value.length > 0) {
    const data = tableSelected.value[0]
    pageContentRef.value?.editClick(data, true)
    nextTick(() => {
      const newArray = tableSelected.value.slice(1)
      dialogRef.value?.changeSelected(newArray)
    })
  }
}

/** 编辑下一条记录 */
const editNext = (data) => {
  console.log('editNext被调用，数据:', data)
  if (pageContentRef.value && pageContentRef.value.editClick) {
    pageContentRef.value.editClick(data, true)
  } else {
    console.error('pageContentRef.value不存在或没有editClick方法')
  }
}

const [dialogRef, infoInit, addClick, editBtnClick] = useDialog(
  addCallBack,
  editCallback,
  '添加',
  '编辑'
)

// 对话框宽度
const dialogWidth = ref('600px')
// 搜索数据
const searchData = computed(() => {
  return pageContentRef.value?.finalSearchData
})

/** 获取宽度值 */
const getWidth = (width) => {
  if (typeof width === 'number') {
    return width + 'px'
  } 
  return width
}

/** 搜索方法 */
const search = () => {
  pageSearchRef.value?.search()
}

/** 请求前处理查询参数 */
const beforeSend = (queryInfo) => {
  if (queryInfo.dateRange && Array.isArray(queryInfo.dateRange)) {
    const dateRange = queryInfo.dateRange
    queryInfo['params[beginTime]'] = dateRange[0]
    queryInfo['params[endTime]'] = dateRange[1]
    delete queryInfo.dateRange
  }
}

// 权限配置
const permission = ref({
  add: 'system:operations:add',
  edit: 'system:operations:edit',
  del: 'system:operations:remove',
})

/** 列显示变更处理 */
const onChangeShowColumn = (filterArr) => {
  tableHideItems.value = filterArr
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download(
    'system/operations/export',
    {
      ...searchData.value,
    },
    `operations_${new Date().getTime()}.xlsx`
  )
}

/** 删除操作记录 */
const handleDelete = async (row) => {
  console.log('删除操作被触发，接收到的数据:', JSON.stringify(row))
  
  // 检查行数据的结构和ID字段
  if (Array.isArray(row)) {
    console.log('批量删除，第一行数据的所有字段:', Object.keys(row[0]))
  } else if (row && typeof row === 'object') {
    console.log('单行删除，所有字段:', Object.keys(row))
  }
  
  // 尝试使用不同的ID字段名称
  const possibleIdFields = ['logId', 'operationsId', 'id', 'operationId'];
  let idFieldFound = null;
  
  if (Array.isArray(row) && row.length > 0) {
    for (const field of possibleIdFields) {
      if (row[0][field] !== undefined) {
        idFieldFound = field;
        console.log(`在数组数据中找到ID字段: ${field} = ${row[0][field]}`);
        break;
      }
    }
  } else if (row && typeof row === 'object') {
    for (const field of possibleIdFields) {
      if (row[field] !== undefined) {
        idFieldFound = field;
        console.log(`在单条数据中找到ID字段: ${field} = ${row[field]}`);
        break;
      }
    }
  }
  
  // 根据找到的ID字段提取值
  let logIds;
  if (idFieldFound) {
    logIds = Array.isArray(row) ? row.map(item => item[idFieldFound]) : row[idFieldFound];
  } else {
    logIds = Array.isArray(row) ? row.map(item => item.logId) : row.logId;
  }
  
  console.log('提取的ID值:', logIds)
  
  if (!logIds || (Array.isArray(logIds) && logIds.length === 0)) {
    proxy.$modal.msgError('未获取到有效Id')
    return
  }
  
  proxy.$modal.confirm(`确认删除操作记录编号为"${logIds}"的数据项？`).then(async () => {
    const [res, err] = await to(delOperations(logIds))
    if (res) {
      proxy.$modal.msgSuccess('删除成功')
      search()
    } else {
      proxy.$modal.msgError(err.message || '删除失败')
    }
  }).catch(() => {})
}

/** 表单提交前处理 */
const handleBeforeCommit = (form) => {
  console.log("提交前的原始表单数据:", JSON.stringify(form))
  
  // 确保操作类型是字符串内容而不是ID
  if (form.operationType !== undefined) {
    // 缓存原始值用于日志
    const originalType = form.operationType
    
    // 强制检查并转换操作类型为字符串值
    try {
      // 直接从数据字典中查找并替换
      const typeDict = file_operations_type.value || []
      console.log('可用的操作类型字典:', JSON.stringify(typeDict))
      
      // 查找匹配的字典项
      const typeValue = typeof originalType === 'string' ? parseInt(originalType, 10) : originalType
      const matchItem = typeDict.find(item => {
        const itemValue = typeof item.value === 'string' ? parseInt(item.value, 10) : item.value
        return itemValue === typeValue
      })
      
      if (matchItem) {
        console.log(`成功转换操作类型: ${originalType}(ID) => ${matchItem.label}(文本)`)
        form.operationType = matchItem.label // 使用标签作为提交内容
      } else {
        console.error(`未找到匹配的操作类型! 原始值: ${originalType}, 类型: ${typeof originalType}`)
        console.error('可用的字典项:', JSON.stringify(typeDict))
        
        // 如果是字符串且不是数字，则可能已经是标签值
        if (typeof originalType === 'string' && isNaN(parseInt(originalType, 10))) {
          console.log(`保留非数字字符串值: ${originalType}`)
        } else {
          // 最后尝试强制转换 - 这是一个备用方案
          proxy.$modal.msgWarning(`操作类型映射失败，请检查数据！`)
        }
      }
    } catch (error) {
      console.error('操作类型转换出错:', error)
    }
  }
  
  // 检查并确保ID字段存在
  const possibleIdFields = ['logId', 'operationsId', 'id', 'operationId'];
  let idFieldFound = null;
  
  for (const field of possibleIdFields) {
    if (form[field] !== undefined) {
      idFieldFound = field;
      console.log(`在表单数据中找到ID字段: ${field} = ${form[field]}`);
      break;
    }
  }
  
  if (idFieldFound) {
    // 这是编辑操作，确保所有必要字段都存在
    console.log(`编辑操作，${idFieldFound}:`, form[idFieldFound])
    
    // 检查必要字段
    const requiredFields = ['operationType', 'operationContent', 'userId'];
    const missingFields = requiredFields.filter(field => form[field] === undefined);
    
    if (missingFields.length > 0) {
      console.error('提交表单缺少必填字段:', missingFields.join(', '));
      proxy.$modal.msgError(`表单缺少必填字段: ${missingFields.join(', ')}`);
      return false;
    }
  }
  
  console.log("处理后的最终提交数据:", JSON.stringify(form));
  return form
}
</script>

<style scoped lang="scss">
.page {
  :deep(.statusClass .el-radio-group) {
    width: 100%;
    justify-content: space-between;
    .el-radio {
      margin-right: 0;
    }
  }
}
</style>
